package homework;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/**
 * 服务器升级版
 */
public class Server2 {
    private ServerSocket ServerSocket;


    public Server2() {
        try {
            System.out.println("正在建立服务器");
            ServerSocket = new ServerSocket(8099);
            System.out.println("服务器已建立");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start() {
        try {
            int i = 1;
            while (true) {
                System.out.println("正在等待客户端连接");
                Socket socket = ServerSocket.accept();
                System.out.println(i + "个客户端已连接");
                i++;
                ClientHandler handler = new ClientHandler(socket);
                Thread t = new Thread(handler);
                t.start();

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Server2 server2 = new Server2();
        server2.start();
    }
}

class ClientHandler implements Runnable {
    private Socket socket;

    public ClientHandler(Socket socket) {
        this.socket = socket;
    }

    public void run() {
        try {
        InputStream in = socket.getInputStream();
        InputStreamReader isr = new InputStreamReader(in, StandardCharsets.UTF_8);
        BufferedReader br = new BufferedReader(isr);
            String message;
            while ((message = br.readLine()) != null) {
                System.out.println(message);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

